﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Globalization;

namespace Tanmia.Basis
{
    [Serializable]
    public class ObjectValidator
    {
        private readonly object instance;

        public ICollection<ValidationResult> ValidationResults { get; private set; }

        public ObjectValidator(object instance)
        {
            if (instance == null)
                throw new ArgumentNullException("Your instance is incorrect!", new Exception("The parameter <instance> could not equals null."));

            this.instance = instance;
        }

        public string Error
        {
            get
            {
                ValidationResults = new List<ValidationResult>();
                ValidationContext ami = new ValidationContext(instance, null, null);
                Validator.TryValidateObject(instance, new ValidationContext(instance, null, null), ValidationResults, true);

                StringBuilder errorBuilder = new StringBuilder();

                foreach (ValidationResult vr in ValidationResults)
                {
                    errorBuilder.AppendInNewLine(vr.ErrorMessage);
                }

                return errorBuilder.ToString();
            }
        }

        public string this[string columnName]
        {
            get
            {

                ValidationResults = new List<ValidationResult>();

                PropertyDescriptor property = TypeDescriptor.GetProperties(instance)[columnName];

                if (property == null)
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                            "The specified member {0} was not found on the instance {1}", columnName, GetType()));

                Validator.TryValidateProperty(property.GetValue(instance), new ValidationContext(instance, null, null) { MemberName = columnName }, ValidationResults);

                StringBuilder errorBuilder = new StringBuilder();
                foreach (ValidationResult validationResult in ValidationResults)
                    errorBuilder.AppendInNewLine(validationResult.ErrorMessage);

                return errorBuilder.ToString();
            }
        }

    }
}
